/*
 * ActivitatsServiceImpl.java
 *
 */

package org.wooxes.server;

import org.wooxes.client.Activitat;
import org.wooxes.client.Arxiu;
import org.wooxes.client.Assignatura;
import org.wooxes.client.Comment;
import org.wooxes.client.Entrega;
import org.wooxes.client.ActivitatsService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.*;
import java.text.SimpleDateFormat;
//import java.util.Collections;
import java.util.Date;
import java.util.Vector;

public class ActivitatsServiceImpl extends RemoteServiceServlet implements ActivitatsService {
    public Vector getAssignatures(){
        ConnexioSQL connexio = new ConnexioSQL();
        Connection conn = connexio.getConnection();
        if(conn == null){
            return null;
        }
        
        Vector vc = new Vector();
        try{
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("SELECT id, nom FROM assignatura order by nom");

            while (rs.next()){
                Assignatura a = new Assignatura();
                a.setId(rs.getInt("id"));
                a.setNom(rs.getString("nom"));
                vc.add(a);
            }
            rs.close();
            statement.close();
        }
        catch(Exception e){
            System.out.println(e);
            return null;
        }

        return vc;
    }
    
    public Vector getActivitats(String s){
        ConnexioSQL connexio = new ConnexioSQL();
        Connection conn = connexio.getConnection();
        if(conn == null){
            return null;
        }
        
        Vector vc = new Vector();
        try{
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(
                    "SELECT a.id, a.nom, a.data, a.hora, a.descripcio, a.adjunt " +
                    "FROM activitat a, assignatura s " +
                    "WHERE a.idassignatura = s.id AND " +
                    "s.nom = '" + s + "' " +
                    "ORDER BY a.nom");
            
            while (rs.next()){
                Activitat ac = new Activitat();
                
                ac.setId(rs.getInt("id"));
                ac.setNom(rs.getString("nom"));
                ac.setDescripcio(rs.getString("descripcio"));
                ac.setAdjunt(rs.getString("adjunt"));
                //Data
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date d = format.parse(rs.getString("data")+" "+rs.getString("hora"));
                ac.setData(d);
                
                vc.add(ac);
            }
            rs.close();
            statement.close();
        }
        catch(Exception e){
            System.out.println(e);
            return null;
        }

        return vc;
    }
    
    public Vector getEntregues(int id){
        ConnexioSQL connexio = new ConnexioSQL();
        Connection conn = connexio.getConnection();
        if(conn == null){
            return null;
        }
        
        Vector vc = new Vector();
        try{
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(
                    "SELECT id, alumne, arxiu, data, hora " +
                    "FROM entrega " +
                    "WHERE idactivitat = " + id + " " +
                    "ORDER BY arxiu");
            
            while (rs.next()){
                Entrega en = new Entrega();
                en.setId(rs.getInt("id"));
                en.setAlumne(rs.getString("alumne"));
                en.setArxiu(rs.getString("arxiu"));
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date d = format.parse(rs.getString("data")+" "+rs.getString("hora"));
                en.setData(d);
                
                vc.add(en);
            }
            rs.close();
            statement.close();
        }
        catch(Exception e){
            System.out.println(e);
            return null;
        }
        
        return vc;
    }
    
    public Vector getLlistaArxius(int id){
        ConnexioSQL connexio = new ConnexioSQL();
        Connection conn = connexio.getConnection();
        if(conn == null){
            return null;
        }
        Vector vc = new Vector();
        try{
            String arxiu = null;
            int activitat = 0;
            
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("SELECT arxiu, idactivitat FROM entrega WHERE id="+id);
            while(rs.next()){
                arxiu = rs.getString("arxiu");
                activitat = rs.getInt("idactivitat");
            }
            rs.close();
            // Si no ha tingut cap resultat
            if( arxiu == null || activitat == 0){
                return null;
            }
            
            ConfiguracioServidor config = new ConfiguracioServidor(conn);
            String ruta = config.getUploadDir();
            
            ruta = ruta + activitat + File.separator + "entregues" + File.separator + arxiu;
            ruta = ruta.substring(0,ruta.lastIndexOf("."));
            getArxiusRecursiu(ruta, vc);
            //Collections.sort(vc);
        }
        catch(Exception e){
            System.out.println(e);
            return null;
        }
        return vc;
    }
    
    private void getArxiusRecursiu(String global, Vector vc){
        getArxiusRecursiu(global,"", vc);
    }
    
    private void getArxiusRecursiu(String global, String relatiu, Vector vc){
        File file = new File(global);
        if (file.exists()){
            if(file.isDirectory()){
                String llista[] = file.list();
                String aux;
                for( int i=0; i < llista.length; i++){
                    aux = File.separator + llista[i];
                    getArxiusRecursiu(global + aux, relatiu + aux, vc);
                }
            }
            else{
                Arxiu arxiu = new Arxiu();
                arxiu.setNom(file.getName());
                arxiu.setRelatiu(relatiu);
                arxiu.setAbsolut(file.getAbsolutePath());
                arxiu.setSize(file.length());
                vc.add(arxiu);
            }
        }
        // Si no existeix, no s'afegirà res
    }

    public Vector getArxiu(String absolut){
        Vector vc = new Vector();
        try{
            Vector vc_comment = getComments(absolut);
            BufferedReader reader = new BufferedReader(new FileReader(absolut));
            String aux;
            int linia = 1;
            while((aux = reader.readLine())!=null){
                Comment comment = new Comment();
                comment.setCodi(aux);
                Comment c_aux = buscarComment(linia, vc_comment);
                if( c_aux != null ){
                    comment.setHTML(c_aux.getHTML());
                    comment.setTipus(c_aux.getTipus());
                }
                vc.add(comment);
                linia++;
            }
        }
        catch(Exception e){
            System.out.println(e);
            return null;
        }
        //System.out.println("Num linies: "+vc.size());
        return vc;
    }
    
    private Vector getComments(String absolut){
        ArxiuXML xml = new ArxiuXML(new File(absolut + ".comment"));
        return xml.getComments();
    }
    
    private Comment buscarComment(int l, Vector v){
        Comment c;
        
        for(int i=0; i<v.size(); i++){
            c = (Comment) v.get(i);
            if(c.getLinia() == l ){
                return c;
            }
            else if(c.getLinia() > l ){
                return null;
            }
        }
        return null;
    }
}
